﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using App.Data;
using App.Core.Extensions;
using System.Data;
using System.Text;
using App.Core.Mail;

public partial class Pages_Private_SubscribePackage : BasePage
{
    protected String _ItemName = String.Empty;
    protected decimal _Price = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            BindPackageList();
        }
    }

    protected void BindPageInfo()
    {
        Page.Title = WebUtil.GetPageTitle("Subscribe to Package");
    }

    protected void BindPackageList()
    {
        UtilityDAO dao = new UtilityDAO();
        DataSet ds = dao.GetDataSet(AppSQL.GET_ACTIVE_WITHCOST_PACKAGE_LIST, null, false);
        rptPackageList.DataSource = ds.Tables[0];
        rptPackageList.DataBind();
    }
    protected void SaveSubscription()
    {
        int packageID = Request.Form["rdbPackage"].ToInt();
        if (packageID > 0)
        {
            BtcHousingEntities context = new BtcHousingEntities();
            var packageSubscription = context.PackageSubscriptions.FirstOrDefault(P => P.CustomerID == SessionCache.CurrentUser.CustomerID && P.ExpireDate >= DateTime.Now);
            if ( packageSubscription == null)
            {
                var package = context.Packages.FirstOrDefault(P => P.ID == packageID);
                PackageSubscription subscription = new PackageSubscription();
                subscription.CustomerID = SessionCache.CurrentUser.CustomerID;
                subscription.PackageID = package.ID;
                subscription.ProductCount = package.ProductLimit;
                subscription.StartDate = DateTime.Now;
                subscription.ExpireDate = DateTime.Now.AddDays(package.Duration);
                
                context.AddToPackageSubscriptions(subscription);
                context.SaveChanges();
                WebUtil.ShowMessageBox(divMessage, String.Format("You have successfully subscribed to the package \"{0}\", You will be notified shortly by btcrealestate.org team.", package.Name.HtmlEncode()), false);
            }
            //else if (packageSubscription.IsActiveSubscription && !packageSubscription.IsPaymentReceived) // Request for Sunscription but payment not receipt.
            //{
            //    WebUtil.ShowMessageBox(divMessage, "You already send subscription request, please wait for activation your subscription package.", true);
            //}
            //else if (packageSubscription.IsActiveSubscription && !packageSubscription.IsPaymentReceived) // Request for Sunscription but payment not receipt.
            //{
            //    WebUtil.ShowMessageBox(divMessage, "You already send subscription request, please wait for activation your subscription package.", true);
            //}
            else
                WebUtil.ShowMessageBox(divMessage, "You already have an active subscription.", true);
        }
    }
    protected void ProcessPackage()
    {
        int packageID = Request.Form["rdbPackage"].ToInt();
        if (packageID > 0)
        {
            BtcHousingEntities context = new BtcHousingEntities();
            var package = context.Packages.FirstOrDefault(P => P.ID == packageID);
            if (package != null)
            {
                SendInvoice(package);
                /* Hide by siddik, 20.09.11
                if (rdbPayOnline.Checked)
                {
                    hdnAction.Value = "PayOnline";
                    _ItemName = package.Name;
                    _Price = package.Price;
                }
                else
                {
                    ///Send the Invoice
                    SendInvoice(package);
                }
                 */
            }
            //PackageSubscription subscription = new PackageSubscription();
            //subscription.CustomerID = SessionCache.CurrentUser.CustomerID;
            //subscription.PackageID = package.ID;
            //subscription.ProductCount = package.ProductLimit;
            //subscription.StartDate = DateTime.Now;
            //subscription.ExpireDate = DateTime.Now.AddDays(package.Duration);            
        }
    }
    protected void SendInvoice(Package package)
    {
        StringBuilder template = new StringBuilder(WebUtil.ReadEmailTemplate(AppConstants.EmailTemplate.COMMON));
        if (template.Length > 0)
        {
            StringBuilder originalTemplateText = new StringBuilder(template.ToString());

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("Dear {0},<br/>", SessionCache.CurrentUser.Contact.Name.HtmlEncode());
            sb.AppendFormat("Please review the invoice below from {0}<br/><br/>", ConfigReader.ProviderCompany.HtmlEncode());
            String invoice = String.Format(@"  <table cellpadding='3' cellspacing='0' style='width:100%; border:#CCCCCC 1px solid; border-collapse:collapse; font-size:10pt;'>
                                    <tr>
                                        <td><b>Serial</b></td>
                                        <td><b>Package Name</b></td>
                                        <td><b>Duration</b></td>
                                        <td><b>Max # of Projects</b></td>
                                        <td><b>Price</b></td>
                                    </tr>
                                    <tr>
                                        <td>1</td>
                                        <td>{0}</td>
                                        <td>{1}</td>
                                        <td>{2}</td>
                                        <td>{3}{4}</td>
                                    </tr>
                                    <tr>
                                        <td colspan='4' style='text-align:right'>Total: </td>
                                        <td>{3}{4}</td>
                                    </tr>
                                </table>",
                        package.Name.HtmlEncode(), package.Duration, package.ProductLimit, package.Currency.Symbol, package.Price);

            sb.Append(invoice);
            //sb.AppendFormat("<b>Note:</b> If you cannot click on the link then Copy it and Paste to your browser's address bar to make your account active.");

            template.Replace(AppConstants.ETConstants.DOMAIN, WebUtil.GetDomainAddress());
            template.Replace(AppConstants.ETConstants.MESSAGE, sb.ToString());
            String fromEmail = ConfigReader.SupportEmail;
            String toEmail = SessionCache.CurrentUser.Contact.Email;

            String subject = String.Format("Invoice from {0}", ConfigReader.ProviderCompany);
            WebUtil.SendMail(fromEmail, toEmail, String.Empty, String.Empty, subject, template.ToString());
            //try
            //{
            //    bool isSent = MailManager.SendMail(toEmail, String.Empty, String.Empty, SessionCache.CurrentUser.LoginName, subject, template.ToString());
            //}
            //catch
            //{
            //    BtcHousingEntities context = new BtcHousingEntities();
            //    EmailMessage message = new EmailMessage();
            //    message.Subject = subject;
            //    message.FromEmail = fromEmail;
            //    message.ToEmail = toEmail;
            //    message.Message = template.ToString();
            //    message.IsSent = false;
            //    message.Created = DateTime.Now;
            //    message.AttemptedOn = DateTime.Now;
            //    context.AddToEmailMessages(message);
            //    context.SaveChanges();
            //}

            ///Send a Notification to Site Admin Also            
            sb.Length = 0;
            sb.AppendFormat("Dear {0} Administrator,<br/><br/>", ConfigReader.ProviderCompany);
            sb.AppendFormat("Following Contact is interested to buy a package for his/her company. Please review the information below:<br/><br/>");
            sb.AppendFormat("<b>Company Info:</b><br/>");
            sb.AppendFormat("<b>Name:</b>{0}<br/>", SessionCache.CurrentUser.Customer.Name.HtmlEncode());
            sb.AppendFormat("<a href='{0}{1}?{2}={3}' traget='_blank'>Click Here to view Company Profile</a><br/><br/>"
                , WebUtil.GetDomainAddress(), AppConstants.Pages.COMPANY_PROFILE, AppConstants.QueryString.ID, SessionCache.CurrentUser.CustomerID);
            sb.AppendFormat("<b>Contact Info:</b><br/>");
            sb.AppendFormat("<b>Name:</b> {0}<br/>",SessionCache.CurrentUser.Contact.Name.HtmlEncode());
            sb.AppendFormat("<b>Email:</b> {0}<br/><br/>", SessionCache.CurrentUser.Contact.Email.HtmlEncode());

            sb.AppendFormat("<b>Package Info:</b><br/>");
            sb.Append(invoice);

            originalTemplateText.Replace(AppConstants.ETConstants.DOMAIN, WebUtil.GetDomainAddress());
            originalTemplateText.Replace(AppConstants.ETConstants.MESSAGE, sb.ToString());
            
            fromEmail = SessionCache.CurrentUser.Contact.Email;
            toEmail = ConfigReader.AdminEmail;
            subject = "Invoice for Package Subscription.";

            WebUtil.SendMail(fromEmail, toEmail, String.Empty, String.Empty, subject, originalTemplateText.ToString());
            //try
            //{
            //    bool isSent = MailManager.SendMail(toEmail, String.Empty, String.Empty, fromEmail, subject, template.ToString());
            //}
            //catch
            //{
            //    BtcHousingEntities context = new BtcHousingEntities();
            //    EmailMessage message = new EmailMessage();
            //    message.Subject = subject;
            //    message.FromEmail = fromEmail;
            //    message.ToEmail = toEmail;
            //    message.Message = template.ToString();
            //    message.IsSent = false;
            //    message.Created = DateTime.Now;
            //    message.AttemptedOn = DateTime.Now;
            //    context.AddToEmailMessages(message);
            //    context.SaveChanges();
            //}

            WebUtil.ShowMessageBox(divMessage, String.Format("You have successfully subscribed to the package \"{0}\", You will be notified shortly by btcrealestate.org team.", package.Name.HtmlEncode()), false);
            pnlFormContainer.Visible = false;
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            ProcessPackage();
            //SaveSubscription();  // Siddik 22.09.11
            //if (rdbPayOnline.Checked)
            //    hdnAction.Value = "PayOnline";
            //else
            //{
            //    SendInvoice();
            //}
        }
    }
}